package org.jeecg.modules.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.system.constant.CommonConstant;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.mapper.SysUserRoleMapper;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @Author scott
 * @since 2018-12-21
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    @Autowired
    private ISysRoleService sysRoleService;

    @Override
    public Boolean isAdmin(String userId){
//        baseMapper.selectList(new LambdaQueryWrapper<Sys>().eq(SysUser::getId:))
        List<SysRole> roleList = baseMapper.selectRoleList(userId);
        for (SysRole role : roleList) {
            if(CommonConstant.ROLE_ADMIN.equals(role.getRoleCode())){
                return true;
            }
        }
        return false;
    }

    @Override
    public void saveBatchWithRoleCode(List<SysUser> listSysUsers) {
        Map<String, List<SysUser>> map = listSysUsers.stream()
                .filter(item-> StringUtils.isNotEmpty(item.getRoleCode()))
                .collect(Collectors.groupingBy(SysUser::getRoleCode));

        for (String roleCode : map.keySet()) {
            SysRole role = sysRoleService.getOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleCode,roleCode));
            super.saveBatch(map.get(roleCode).stream()
                    .map(item->new SysUserRole(item.getId(),role.getId()))
                    .collect(Collectors.toList()));
        }
    }

}
